package com.hang.gymmanager.controller;

/**
 * @author wyq
 * @version v1.0.0
 * @explain
 * @date 2024/3/30 10:10
 */

import cn.hutool.core.lang.Snowflake;
import cn.hutool.http.ContentType;
import com.hang.gymmanager.config.AlipayConfig;
import com.hang.gymmanager.req.AliPayReq;
import com.hang.gymmanager.service.AlipayService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付控制器
 *
 * @author javgo.cn
 * @date 2024/1/13
 */
@Controller
@RequestMapping("/alipay")
@RequiredArgsConstructor
@CrossOrigin
public class AlipayController {

    private final AlipayConfig alipayConfig;

    private final AlipayService alipayService;

    /**
     * pc端创建订单
     * @param aliPayReq
     * @param response
     * @throws IOException
     */
    @GetMapping("/pcPayment")
    public void pcPayment(AliPayReq aliPayReq, HttpServletResponse response) throws IOException {
        response.setContentType(ContentType.TEXT_HTML.getValue() + ";charset=" + alipayConfig.getCharset());
        Map<String, String> map = alipayService.initiatePcPayment(aliPayReq);
        response.getWriter().write(map.get("formHtml"));
        response.getWriter().flush();
        response.getWriter().close();
    }

//    @GetMapping("/mobilePayment")
//    public void mobilePayment(AliPayReq aliPayReq, HttpServletResponse response) throws IOException {
//        response.setContentType(ContentType.TEXT_HTML.getValue() + ";charset=" + alipayConfig.getCharset());
//        alipayService.initiateMobilePayment(aliPayReq);
//        //response.getWriter().write(result.getData().toString());
//        response.getWriter().flush();
//        response.getWriter().close();
//    }
//
    @PostMapping("/notify")
    @ResponseBody
    public void processPaymentNotification(HttpServletRequest request) {
        System.out.println("阿里异步回调进来了");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        requestParams.keySet().forEach(r -> params.put(r, request.getParameter(r)));
        alipayService.processPaymentNotification(params);
        return;
    }
//
//    @GetMapping("/queryPaymentStatus")
//    @ResponseBody
//    public void queryPaymentStatus(String outTradeNo, String tradeNo) {
//        alipayService.queryPaymentStatus(outTradeNo, tradeNo);
//        return;
//    }
//
//    public static void main(String[] args) {
//        Snowflake snowflake = new Snowflake();
//        long l = snowflake.nextId();
//        System.out.println(l);
//    }
}
